package com.hz.friends.fragment.nearby;

import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;

import android.R.color;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.graphics.drawable.AnimationDrawable;
import android.graphics.drawable.BitmapDrawable;
import android.media.MediaPlayer;
import android.media.MediaPlayer.OnCompletionListener;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.AttributeSet;
import android.util.TypedValue;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.AdapterView.OnItemClickListener;

import com.alibaba.fastjson.JSONArray;
import com.androidquery.AQuery;
import com.androidquery.callback.AjaxCallback;
import com.androidquery.callback.AjaxStatus;
import com.androidquery.callback.BitmapAjaxCallback;
import com.avos.avoscloud.AVException;
import com.avos.avoscloud.AVGeoPoint;
import com.avos.avoscloud.AVUser;
import com.handmark.pulltorefresh.library.PullToRefreshBase;
import com.handmark.pulltorefresh.library.PullToRefreshListView;
import com.handmark.pulltorefresh.library.PullToRefreshBase.OnRefreshListener2;
import com.hz.friends.activity.MaintabsActivity;
import com.hz.friends.activity.R;
import com.hz.friends.activity.UserInfosActivity;
import com.hz.friends.application.CustomApplication;
import com.hz.friends.chat.GroupChatActivity;
import com.hz.friends.chat.entity.IMChatMessage;
import com.hz.friends.fragment.contacts.FriendContacts;
import com.hz.friends.fragment.nearby.NearByRoomListView.HotRoomAdpter;
import com.hz.friends.serverrequest.ALUserEngine;
import com.hz.friends.serverrequest.ALCCPEngine.ALGroupType;
import com.hz.friends.serverrequest.ALEngineConfig.ALUserGender;
import com.hz.friends.serverrequest.ALEngineConfig.CallBack;
import com.hz.friends.utils.BitmapUtils;
import com.hz.friends.utils.DensityUtil;
import com.hz.friends.utils.MLog;
import com.hz.friends.utils.UtilTools;

public class NearbyuserListView extends BaseNearbyListView {
	private Context mcontext;
	private PullToRefreshListView mlistview;
	private TextView txv_nodata;
	private View view;
	private FriendContacts fc;
	private MediaPlayer mMediaPlayer = new MediaPlayer();
	private String TAG = "NearbyuserListView";
	private final int limit = 20;// 分页
	private int skip = 0;// 跳过记录条数
	private NearByUserAdpter madpter;
	private String[] tipsarr = { "附近没有搜索到用户", "获取位置失败,点击重新获取" };

	public NearbyuserListView(Context context) {
		this.mcontext = context;
		view = LayoutInflater.from(context).inflate(R.layout.nearby_item, null);
		mlistview = (PullToRefreshListView) view.findViewById(R.id.mlistview);
		txv_nodata = (TextView) view.findViewById(R.id.txv_nodata);
		txv_nodata.setText(tipsarr[0]);
		init();
		initEvents();
	}

	public void getData() {
		// fc = new FriendContacts(mlistview, mcontext, 3,lat,lon,userGender);
		// fc.setLocation(lat, lon);
		// fc.setUserGender(userGender);
		madpter.clearData();
		madpter.notifyDataSetChanged();
		uploadNearbyusers();
	}

	private void initEvents() {
		mlistview.setOnRefreshListener(new OnRefreshListener2<ListView>() {

			@Override
			public void onPullUpToRefresh(
					PullToRefreshBase<ListView> refreshView) {

			}

			@Override
			public void onPullDownToRefresh(
					PullToRefreshBase<ListView> refreshView) {
				// onRefresh();
				txv_nodata.setVisibility(View.GONE);
				madpter.clearData();
				txv_nodata.setVisibility(View.GONE);
				uploadNearbyusers();
			}
		});
		mlistview.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> parent, View view,
					int position, long id) {
				// CustomApplication.getInstance().currgroup =
				// madpter.getItem(position-1);
				// Intent intent = new Intent(mcontext,GroupChatActivity.class);
				// intent.putExtra("titlename",
				// madpter.getItem(position-1).getString("name"));
				// intent.putExtra("isGroup", true);
				// mcontext.startActivity(intent);

			}
		});
		txv_nodata.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				if (txv_nodata.getText().toString().contains("获取位置失败")
						&& mcontext != null) {
					mcontext.sendBroadcast(new Intent("INTENT_START_LOCATION"));
					MLog.i(TAG,
							"restart location sendbroadcast INTENT_START_LOCATION");
				}
			}
		});
	}

	public View getView() {
		return view;
	}

	private void init() {
		// int diverheight = (int) TypedValue.applyDimension(
		// TypedValue.COMPLEX_UNIT_DIP, 5, mcontext.getResources()
		// .getDisplayMetrics());
		// mlistview.getRefreshableView().setDivider(
		// mcontext.getResources()
		// .getDrawable(android.R.color.transparent));
		// mlistview.getRefreshableView().setDividerHeight(diverheight);

		madpter = new NearByUserAdpter();
		mlistview.setAdapter(madpter);
	}

	// onSearchs 搜索附近的用户
	private void uploadNearbyusers() {
		MLog.i(TAG, "uploadNearbyusers  lat:" + lat + "  lon:" + lon);
		txv_nodata.setText(tipsarr[0]);
		if (lon == 0 || lat == 0) {
			mlistview.onRefreshComplete();
			txv_nodata.setText(tipsarr[1]);
			txv_nodata.setVisibility(View.VISIBLE);
			return;
		}
		ALUserEngine.defauleEngine().searchUserWithNear(lat, lon, 1000,
				userGender, limit, new ArrayList<AVUser>(), new CallBack() {

					@Override
					public void done(Object object, AVException avexception) {
						MLog.i(TAG, "uploadNearbyusers avexception:"
								+ avexception + "  object:" + object);
						mlistview.onRefreshComplete();
						txv_nodata.setVisibility(View.GONE);
						if (avexception == null) {
							List<AVUser> data = (List<AVUser>) object;

							if (data == null || data.size() == 0) {
								txv_nodata.setVisibility(View.VISIBLE);
							}
							madpter.setData(data);
							madpter.notifyDataSetChanged();
						} else {
							avexception.printStackTrace();
							((MaintabsActivity) mcontext)
									.showSysToast("搜索附近用户错误");
						}

					}
				});

		uploadFolloweeList();
	}

	// 我的关注
	private void uploadFolloweeList() {
		ALUserEngine.defauleEngine().getFolloweeList(AVUser.getCurrentUser(),
				100, 0, new CallBack() {
					@Override
					public void done(Object object, AVException avexception) {
						MLog.i(TAG, "uploadFolloweeList avexception:"
								+ avexception + "  object:" + object);

						mlistview.onRefreshComplete();
						if (avexception == null) {
							HashMap<String, List> map = (HashMap<String, List>) object;
							if (map == null) {
								madpter.setFollowData(null);
								return;
							}
							List<AVUser> data = map.get("followees");
							madpter.setFollowData(data);
						} else {
							avexception.printStackTrace();
						}

					}
				});
	}

	class NearByUserAdpter extends BaseAdapter {
		private List<AVUser> userlist = new ArrayList<AVUser>();
		private List<AVUser> followlist = new ArrayList<AVUser>();
		private AQuery aq = new AQuery(mcontext);

		@Override
		public int getCount() {
			return userlist.size();
		}

		@Override
		public Object getItem(int position) {
			return null;
		}

		@Override
		public long getItemId(int position) {
			return 0;
		}

		public void setData(List<AVUser> userlist) {
			if (userlist == null)
				userlist = new ArrayList<AVUser>();
			this.userlist = userlist;
		}

		// public void addData(List<AVUser> userlist) {
		// if (userlist == null)
		// return;
		// this.userlist.addAll(userlist);
		// }

		public void setFollowData(List<AVUser> userlist) {
			if (userlist == null) {
				userlist = new ArrayList<AVUser>();
			}
			this.followlist = userlist;
			this.notifyDataSetChanged();
		}

		public void clearData() {
			this.userlist.clear();
		}

		@Override
		public View getView(int position, View convertView, ViewGroup parent) {
			final ViewHolder holder;
			convertView = null;
			if (convertView == null) {
				holder = new ViewHolder();
				convertView = LayoutInflater.from(mcontext).inflate(
						R.layout.adpter_nearbyusers, null);
				// holder = new ViewHolder();
				holder.imv_heard = (ImageView) convertView
						.findViewById(R.id.imv_heard);
				holder.txv_name = (TextView) convertView
						.findViewById(R.id.txv_name);
				holder.btn_special = (Button) convertView
						.findViewById(R.id.btn_special);
				holder.layoutxx = (LinearLayout) convertView
						.findViewById(R.id.layoutxx);
				holder.txv_signature = (TextView) convertView
						.findViewById(R.id.txv_signature);
				holder.layout_sex = (LinearLayout) convertView
						.findViewById(R.id.layout_sex);
				holder.imv_sex = (ImageView) convertView
						.findViewById(R.id.imv_sex);
				holder.txv_age = (TextView) convertView
						.findViewById(R.id.txv_age);
				holder.layout_voice = (LinearLayout) convertView
						.findViewById(R.id.layout_voice);
				holder.txv_voiceduration = (TextView) convertView
						.findViewById(R.id.txv_voiceduration);
				holder.imv_speakanim = (ImageView) convertView
						.findViewById(R.id.imv_speakanim);
				holder.txv_durationkm = (TextView) convertView
						.findViewById(R.id.txv_durationkm);
				holder.txv_timeafter = (TextView) convertView
						.findViewById(R.id.txv_timeafter);

				convertView.setTag(holder);
			} else {
				holder = (ViewHolder) convertView.getTag();
			}

			final AVUser avuser = userlist.get(position);
			String name = avuser.getUsername();
			final String nickname = avuser.getString("nickname");
			String heardurl = avuser.getString("headViewURL");
			String signature = avuser.getString("signature");
			if (TextUtils.isEmpty(signature))
				signature = "No content";
			Date brithday = avuser.getDate("brithday");
			int gender = avuser.getInt("gender");
			int introductionOfVoiceOfDuration = avuser
					.getInt("introductionOfVoiceOfDuration");
			final String introductionOfVoiceURL = avuser
					.getString("introductionOfVoiceURL");
			AVGeoPoint togeopoint = avuser.getAVGeoPoint("location");
			Date togeopointdate = avuser.getDate("lastUpdateLocationDate");

			final int width = DensityUtil.dip2px(mcontext, 70);
			// default image
			Bitmap crclebitmap = BitmapUtils.drawCycleImage("#c4c4c5", width);
			Bitmap crclestrokebitmap = BitmapUtils.getCircleStrokbitmap(
					mcontext, crclebitmap, width, 1, "#eeeeee");
			holder.imv_heard.setImageBitmap(crclestrokebitmap);
			holder.imv_heard.setBackgroundDrawable(new BitmapDrawable(crclestrokebitmap));

//			aq.ajax(heardurl, Bitmap.class, new AjaxCallback<Bitmap>() {
//				@Override
//				public void callback(String url, Bitmap bitmap,
//						AjaxStatus status) {
//					Bitmap mbitmap = BitmapUtils.getCircleStrokbitmap(mcontext,
//							bitmap, width, 1, "#eeeeee");
//					holder.imv_heard.setImageBitmap(mbitmap);
//				}
//			});
			aq.id(holder.imv_heard).image(heardurl,true,true,width,0,new BitmapAjaxCallback(){
				@Override
				protected void callback(String url, ImageView iv, Bitmap bm,
						AjaxStatus status) {
					super.callback(url, iv, bm, status);
					Bitmap mbitmap = BitmapUtils.getCircleStrokbitmap(mcontext,
							bm, width, 1, "#eeeeee");
					holder.imv_heard.setImageBitmap(mbitmap);
					holder.imv_heard.setBackgroundColor(Color.TRANSPARENT);
				}
			});
			holder.txv_name.setText(nickname);
			holder.txv_signature.setText(signature);
			holder.txv_age.setText(String.valueOf(UtilTools
					.getAgeByBirthday(brithday))); // 年龄
			setDistance(togeopoint, holder.txv_durationkm);
			if (togeopointdate != null) {
				holder.txv_timeafter.setText(UtilTools.getdurtionTimeFormat(
						togeopointdate, new Date()));
			} else {
				holder.txv_timeafter.setText("no time");
			}
			holder.imv_heard.setOnClickListener(new OnClickListener() {

				@Override
				public void onClick(View v) {
					((CustomApplication) ((Activity) mcontext).getApplication()).user = avuser;
					Bundle bundle = new Bundle();
					bundle.putInt("isother", 1);
					Intent intent = new Intent(mcontext,
							UserInfosActivity.class);
					intent.putExtras(bundle);
					mcontext.startActivity(intent);
				}
			});
			holder.layoutxx.setOnClickListener(new OnClickListener() {

				@Override
				public void onClick(View v) {
					CustomApplication.getInstance().user = avuser;
					Intent intent = new Intent(mcontext,
							GroupChatActivity.class);
					intent.putExtra("titlename", nickname);
					intent.putExtra("isGroup", false);
					mcontext.startActivity(intent);
				}
			});
			holder.btn_special.setOnClickListener(new OnClickListener() {

				@Override
				public void onClick(View v) {
					addFriend(avuser, holder.btn_special);
				}
			});
			if (gender == ALUserGender.ALUserGenderOfFemale.get_value()) {// 女性
				holder.layout_sex
						.setBackgroundResource(R.drawable.shape_bj_icwoman_xml);
				holder.imv_sex.setImageResource(R.drawable.ic_woman);
			} else {// 男性
				holder.layout_sex
						.setBackgroundResource(R.drawable.shape_bj_icman_xml);
				holder.imv_sex.setImageResource(R.drawable.ic_man);
			}

			getAttenState(avuser, holder.btn_special);

			// 语音
			if (introductionOfVoiceOfDuration > 0) {
				holder.layout_voice.setVisibility(View.VISIBLE);
				holder.txv_voiceduration.setText(String
						.valueOf(introductionOfVoiceOfDuration) + "\'\'");
				holder.txv_voiceduration.setTag(introductionOfVoiceURL);
			} else {
				holder.layout_voice.setVisibility(View.INVISIBLE);
			}

			holder.layout_voice.setOnClickListener(new OnClickListener() {

				@Override
				public void onClick(View v) {
					playMusic(introductionOfVoiceURL, holder.imv_speakanim);
				}
			});
			return convertView;
		}

		private void setDistance(AVGeoPoint togeopoint, TextView txv) {
			AVGeoPoint mgeopoint = AVUser.getCurrentUser().getAVGeoPoint(
					"location");
			if (mgeopoint == null || togeopoint == null) {
				txv.setText("unknow");
				return;
			}
			double distan = mgeopoint.distanceInKilometersTo(togeopoint);
			DecimalFormat df = new DecimalFormat("#.##");
			double km = distan / 1000;
			txv.setText(df.format(km) + " km");

		}

		private void addFriend(final AVUser avuser, final Button btn) {
			if (btn.getTag() != null) {// 移除关注
				ALUserEngine.defauleEngine().removeFollow(avuser,
						new CallBack() {

							@Override
							public void done(Object object,
									AVException avexception) {
								if (avexception == null) {
									((MaintabsActivity) mcontext)
											.showSysToast("取消关注成功");
									btn.setText("Attention");
									btn.setBackgroundResource(R.drawable.shape_nearby_attention);
									btn.setTag(null);
								} else {
									((MaintabsActivity) mcontext)
											.showSysToast("取消关注失败");
									avexception.printStackTrace();
								}
							}
						});
			} else {// 添加关注
				ALUserEngine.defauleEngine().addFollow(avuser, null,
						new CallBack() {

							@Override
							public void done(Object object,
									AVException avexception) {
								if (avexception == null) {
									((MaintabsActivity) mcontext)
											.showSysToast("关注成功");
									btn.setText("Cancel");
									btn.setBackgroundResource(R.drawable.shape_nearby_attention2);
									btn.setTag("1");
								} else {
									((MaintabsActivity) mcontext)
											.showSysToast("关注失败");
									avexception.printStackTrace();
								}
							}
						});
			}

		}

		private void getAttenState(AVUser avuser, Button btn) {
			for (int i = 0; i < this.followlist.size(); i++) {
				AVUser user = this.followlist.get(i);
				if (avuser.getObjectId().equals(user.getObjectId())) {
					btn.setText("Cancel");
					btn.setBackgroundResource(R.drawable.shape_nearby_attention2);
					btn.setTag("1");
					return;
				}
			}
			btn.setText("Attention");
			btn.setBackgroundResource(R.drawable.shape_nearby_attention);
			btn.setTag(null);

		}

	}

	private static class ViewHolder {
		ImageView imv_heard; //
		TextView txv_name;//
		LinearLayout layoutxx;
		Button btn_special;
		TextView txv_signature; // 签名
		LinearLayout layout_sex; // 性别布局
		ImageView imv_sex; // 性别图标
		TextView txv_age; // 年龄
		LinearLayout layout_voice;// 声音
		TextView txv_voiceduration; // 声音
		ImageView imv_speakanim; // 声音动画
		TextView txv_durationkm; // 距离
		TextView txv_timeafter; // 距离更新时间

	}
    private ImageView palyingImageView = null;
	/**
	 * @Description
	 * @param name
	 */
	private void playMusic(final String url, final ImageView iv_voice) {
		try {
			synchronized (mMediaPlayer) {// 清除上条消息的状态
				if (mMediaPlayer.isPlaying()) {
					mMediaPlayer.stop();
					if (palyingImageView != null) {
						AnimationDrawable lastvoiceAnimation = (AnimationDrawable) palyingImageView
								.getDrawable();
						if (lastvoiceAnimation != null)
							lastvoiceAnimation.stop();
						palyingImageView.setVisibility(View.INVISIBLE);
					}
				}
				iv_voice.setVisibility(View.VISIBLE);
				final AnimationDrawable voiceAnimation = (AnimationDrawable) iv_voice
						.getDrawable();
				mMediaPlayer.reset();
				mMediaPlayer.setDataSource(url);
				mMediaPlayer.prepare();
				mMediaPlayer.start();
				voiceAnimation.start();
				palyingImageView = iv_voice;
				mMediaPlayer
						.setOnCompletionListener(new OnCompletionListener() {
							public void onCompletion(MediaPlayer mp) {
								voiceAnimation.stop();
								iv_voice.setVisibility(View.INVISIBLE);
							}
						});
			}
		} catch (Exception e) {
			e.printStackTrace();
		}

	}

}
